package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cari.oa.domain.SoftProjectEntity;
import com.cari.oa.domain.SysDeptEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.domain.SysUserEntity;
import com.cari.oa.service.SoftProjectService;
import com.cari.oa.service.SysDeptService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.service.SysUserService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.DateUtils;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;


/**
* Title: softProjectController
* Description: 软件项目列表
* Company: cari 
* @author  hjx 
* @date    2013-1-16
*/
@Controller
@SessionAttributes("username")
@RequestMapping("/soft/project/")
public class SoftProjectController {

	@Resource
	private SoftProjectService softProjectService;
	
	@Resource
	private SysDictItemService sysDictItemService;
	
	@Resource
	private SysUserService sysUserService;
	
	@Resource
	private SysDeptService sysDeptService;
	
	public static final String MODULE_NAME = "SOFT_PROJECT_MANAGER";
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
	
    @RequestMapping("/list.do")
    public String list(String name, String status, Date starttime, Date endtime, Integer curPage, ModelMap modelMap) {
      	if(curPage == null) curPage = 1;
        long totalRecords = softProjectService.getCount(name, status, starttime,endtime);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        List<SoftProjectEntity> softProjectList = softProjectService.getPage(name, status, starttime,endtime, curPage, Contants.PAGE_SIZE);
        List<SysDictItemEntity>  dictItemList = sysDictItemService.getItemsByGroupName("softProjectStatus");
        Map<String, String> gNameMap = new HashMap<String, String>();
        modelMap.addAttribute("softProjectList", softProjectList);
        modelMap.addAttribute("dictItemList", dictItemList);
        modelMap.addAttribute("gNameMap", gNameMap);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);
        modelMap.addAttribute("name", name);
        modelMap.addAttribute("status", status);
        modelMap.addAttribute("startTime", DateUtils.date2Str(starttime, DateUtils.NORMAL_FORMAT));
        modelMap.addAttribute("endTime", DateUtils.date2Str(endtime, DateUtils.NORMAL_FORMAT));
    
        return "soft/project/list";
    }
    
    @RequestMapping(value = "/insert.do", method = RequestMethod.GET)
    public String enterInsert(String qs, ModelMap modelMap) {
        List<SysDictItemEntity>  dictItemList = sysDictItemService.getItemsByGroupName("softProjectStatus");
        List<Map<String,String>> allUserList = sysUserService.getUserAndRole(null);        //所有人员
  	    List<SysDeptEntity> allDeptList = sysDeptService.getAll();
        modelMap.addAttribute("dictItemList", dictItemList);
        modelMap.addAttribute("qs", qs);
        modelMap.addAttribute("allUserList", allUserList);
        modelMap.addAttribute("allDeptList", allDeptList);
        return "soft/project/insert";
    }
    
    @RequestMapping(value = "/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username, 
    		@Valid SoftProjectEntity softProjectEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        String name = softProjectEntity.getName();
        name = name.replace(" ","");
        softProjectEntity.setName(name);
        if (softProjectService.existByEnname(name))
            return Utils.errorJsonResp("项目名称已存在");
        softProjectEntity.setCnName(sysUserService.getByEnname(softProjectEntity.getProjectManager()).getCnname());
        softProjectService.insert(softProjectEntity);
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增软件项目" + softProjectEntity.getName());
        return Utils.normalJsonResp();
    }
    

    /**
    * Title: projectPersonInsert
    * Description:ajax提交的配置操作的请求,并对项目进行人员配备
    * @author    hjx 
    * @date      2013-1-17 
    * @param request
    * @param response
    */
    @RequestMapping(value = "/personConf.do", method = RequestMethod.POST)
    @ResponseBody
	public String projectPersonInsert(@ModelAttribute("username") String username, String projectId,String devenname,String testenname, BindingResult result) {
	
		if(StrUtils.isEmpty(devenname))
		{
			softProjectService.addProjectUserRel(projectId, new ArrayList<String>(),"0");
		}else{
			String[] ps = devenname.split(";");
			List<String> selectedUserEnname = Arrays.asList(ps);
			softProjectService.addProjectUserRel(projectId, selectedUserEnname,"0");
		}
		if(StrUtils.isEmpty(testenname))
		{
			softProjectService.addProjectUserRel(projectId, new ArrayList<String>(),"2");
		}else{
			String[] ps = testenname.split(";");
			List<String> selectedUserEnname = Arrays.asList(ps);
			softProjectService.addProjectUserRel(projectId, selectedUserEnname,"2");
		}
	    SysOperLogController.addOperLog(username, MODULE_NAME, "新增软件项目与人员");
	    return Utils.normalJsonResp();
	}
    
    @RequestMapping(value = "/update.do", method = RequestMethod.GET)
    public String enterEdit(String id, String qs, ModelMap modelMap) {
    	SoftProjectEntity softProject = softProjectService.getById(id);
        List<Map<String,String>> allUserList = sysUserService.getUserAndRole(null);        //所有人员
  	    List<SysDeptEntity> allDeptList = sysDeptService.getAll();
        List<SysDictItemEntity>  dictItemList = sysDictItemService.getItemsByGroupName("softProjectStatus");
        SysUserEntity projectManager = sysUserService.getByEnname(softProject.getProjectManager());
        List<Map<String,String>> userDeptNo = new ArrayList<Map<String,String>>();
        for(Map<String,String> current : allUserList)
        {
        	if(StrUtils.isNotEmpty(current.get("deptNo")) && current.get("deptNo").equals(projectManager.getDeptNo()))
        	{
        		userDeptNo.add(current);
        	}
        }
        modelMap.addAttribute("dictItemList", dictItemList);
        modelMap.addAttribute("sp", softProject);
        modelMap.addAttribute("projectManager", projectManager);
        modelMap.addAttribute("allUserList", allUserList);
        modelMap.addAttribute("userDeptNo", userDeptNo);
        modelMap.addAttribute("allDeptList", allDeptList);
        modelMap.addAttribute("qs", qs);
        return "soft/project/update";
    }
    
    @RequestMapping(value = "/update.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username, 
    		@Valid SoftProjectEntity softProjectEntity,String oldName, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        if(!oldName.equals(softProjectEntity.getName()))
        {
        	String projectName = softProjectEntity.getName();
        	projectName = projectName.replace(" ","").trim();
        	softProjectEntity.setName(projectName);
        	if(softProjectService.getByName(projectName))
        	{
        		 return Utils.errorJsonResp("名称已存在");
        	}
        }
        String name = softProjectEntity.getName();
        name = name.replace(" ","");
        softProjectEntity.setName(name);
        softProjectEntity.setCnName(sysUserService.getByEnname(softProjectEntity.getProjectManager()).getCnname());
        softProjectService.update(softProjectEntity);
        SysOperLogController.addOperLog(username, MODULE_NAME, "修改软件项目" + softProjectEntity.getName());
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/view.do", method = RequestMethod.GET)
    public String enterView(String id, ModelMap modelMap) {
    	SoftProjectEntity softProject = softProjectService.getById(id);
    	List<SysDictItemEntity>  dictItemList = sysDictItemService.getItemsByGroupName("softProjectStatus");
        modelMap.addAttribute("sp", softProject);
        modelMap.addAttribute("dictItemList", dictItemList);
        return "soft/project/view";
    }
    
    /**
    * Title: queryUserList
    * Description: 查询用户列表重新配置人员信息
    * @author    hjx 
    * @date       2013-1-15
    * @param id
    * @param modelMap
    * @return
    */
    @RequestMapping(value = "/personConf.do", method = RequestMethod.GET)
    public String queryUserList(String id,String qs,ModelMap modelMap)
    {
    	  List<Map<String,String>> allUserList = sysUserService.getUserAndRole(null);        //所有人员
    	  List<Map<String,String>> selectedUserList = sysUserService.getUserAndRole(id);     //项目中已选的所有人员
    	  
    	  List<Map<String,String>> selectedDevUsers = new ArrayList<Map<String,String>>();   //项目中已选的开发人员
    	  List<Map<String,String>> selectedTestUsers = new ArrayList<Map<String,String>>();  //项目中已选的测试人员
    	  
    	  List<Map<String,String>> unTestUsers = new ArrayList<Map<String,String>>();        //项目中已选的测试人员
    	  List<Map<String,String>> unDevUsers = new ArrayList<Map<String,String>>();         //项目中已选的开发人员
    	  
    	  List<SysDeptEntity> allDeptList = sysDeptService.getAll();

    	  for(Map<String,String> map : selectedUserList)
    	  {
    		  switch(Integer.valueOf(map.get("type")))
    		  {
    		     case 0:
    		    	 selectedDevUsers.add(map);
    		    	 break;
    		     case 2:
    		    	 selectedTestUsers.add(map);
    		    	 break;
    		  }
    	  }
    	  
    	  for(Map<String,String> map : selectedDevUsers){
	    	  Map<String,String> tempMap = new HashMap<String, String>();
		      tempMap.put("enname", map.get("enname"));
		      tempMap.put("cnname", map.get("cnname"));
		      tempMap.put("deptNo", map.get("deptNo"));
		      if(allUserList.contains(tempMap))
		      {
		    	  allUserList.remove(tempMap);
		      }
          }
    	  unDevUsers = allUserList;
    	  allUserList = sysUserService.getUserAndRole(null);        //所有人员
    	  for(Map<String,String> map : selectedTestUsers){
	    	  Map<String,String> tempMap = new HashMap<String, String>();
		      tempMap.put("enname", map.get("enname"));
		      tempMap.put("cnname", map.get("cnname"));
		      tempMap.put("deptNo", map.get("deptNo"));
		      if(allUserList.contains(tempMap))
		      {
		    	  allUserList.remove(tempMap);
		      }
          }
    	  unTestUsers = allUserList;
         
          StringBuffer devUnToSelect = new StringBuffer();    
          StringBuffer devAllUnToSelect = new StringBuffer(); 
          StringBuffer testUnToSelect = new StringBuffer();    
          StringBuffer testAllUnToSelect = new StringBuffer(); 
    	  for(SysDeptEntity dept : allDeptList)
    	  {
    		  devUnToSelect.append("Move('"+dept.getDeptNo()+"unSelected0','selected0'),");
    		  devAllUnToSelect.append("MoveAll('"+dept.getDeptNo()+"unSelected0','selected0'),");
    		  testUnToSelect.append("Move('"+dept.getDeptNo()+"unSelected2','selected2'),");
    		  testAllUnToSelect.append("MoveAll('"+dept.getDeptNo()+"unSelected2','selected2'),");
    	  }
    	  modelMap.addAttribute("devUnToSelect", devUnToSelect.toString().substring(0, devUnToSelect.toString().toString().length()-1));
    	  modelMap.addAttribute("devAllUnToSelect", devAllUnToSelect.toString().substring(0, devAllUnToSelect.toString().toString().length()-1));
    	  modelMap.addAttribute("devSelectedToUn","leftMove('selected0')");
    	  modelMap.addAttribute("devAllSelectedToUn", "leftMoveAll('selected0')");
    	  
    	  modelMap.addAttribute("testUnToSelect", testUnToSelect.toString().substring(0, testUnToSelect.toString().toString().length()-1));
    	  modelMap.addAttribute("testAllUnToSelect", testAllUnToSelect.toString().substring(0, testAllUnToSelect.toString().toString().length()-1));
    	  modelMap.addAttribute("testSelectedToUn","leftMove('selected2')");
    	  modelMap.addAttribute("testAllSelectedToUn", "leftMoveAll('selected2')");

    	  modelMap.addAttribute("projectId", id);
    	  modelMap.addAttribute("selectedDevUsers", selectedDevUsers);
          modelMap.addAttribute("selectedTestUsers", selectedTestUsers);
          modelMap.addAttribute("unDevUsers", unDevUsers);
          modelMap.addAttribute("unTestUsers", unTestUsers);
    	  modelMap.addAttribute("allDeptList", allDeptList);
    	  modelMap.addAttribute("qs", qs);
          
          modelMap.addAttribute("unSelectedUserList", allUserList);
    	  return "soft/project/personConf";
    }
}
